import {
	domain
} from './config.js'
import {
	useMainStore
} from '@/stores/index.js'
import {getopendId} from '@/utils/api.js'
import {toHome} from '@/utils/utils.js'
const mainStore = useMainStore()

const request = (url, data, method, Typejson = true) => {

	if (!url.includes('http')) url = domain + url
	const requestData = {
		bid: mainStore.bid,
		longitude: mainStore.position.longitude,
		latitude: mainStore.position.latitude,
	};
	data = {
		...data,
		...requestData
	};
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			method,
			data,
			dataType: 'json',
			header: {
				'content-type': Typejson ? 'application/json' : 'application/x-www-form-urlencoded',
				"Authorization": `${mainStore.token}`,
				'token': `${mainStore.token}`
			},
			success: (res) => {
				const result = res.data;
				if(result.code == 401) return getopendId();
				if(result.code == 403) return toHome();
				resolve(result)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

const post = (obj) => {
	return request(obj.url, obj.data, 'POST', obj.Typejson)
}
const get = (obj) => {
	return request(obj.url, obj.data, 'GET', obj.Typejson)
}

export default {
	post,
	get
}